package com.th.listen;

import com.alibaba.fastjson.JSON;
import com.th.common.constants.AuthConstants;
import com.th.common.domain.UsInternalMessage;
import com.th.common.domain.UsUserAuthApply;
import com.th.common.enums.AuthType;
import com.th.common.enums.ExamineResultStatus;
import com.th.common.enums.MessageType;
import com.th.common.utils.SseEmitterUtil;
import com.th.service.UsInternalMessageService;
import com.th.service.UsUserAuthApplyService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author ErrorRua
 * @date 2023/06/25
 * @description:
 */
@Component
public class AuthMessageListener {

    @Autowired
    private UsInternalMessageService usInternalMessageService;

    @Autowired
    private UsUserAuthApplyService usUserAuthApplyService;

    @RabbitListener(queues = AuthConstants.AUTH_INTERNAL_MESSAGE_QUEUE)
    public void authInternalMessageHandler(String id){
        UsUserAuthApply userAuthApply = usUserAuthApplyService.getById(id);

        UsInternalMessage usInternalMessage = buildInternalMessage(userAuthApply);
        usInternalMessageService.save(usInternalMessage);

        // 判断用户是否在线
        if (!SseEmitterUtil.checkUser(userAuthApply.getUserId())) {
            return;
        }

        // 发送消息
        SseEmitterUtil.sendMessage(userAuthApply.getUserId(), JSON.toJSONString(usInternalMessage));
    }


    private UsInternalMessage buildInternalMessage(UsUserAuthApply userAuthApply) {
        UsInternalMessage message = UsInternalMessage.builder()
                .messageType(MessageType.AUTH_IDENTIFY.getType())
                .userId(userAuthApply.getUserId())
                .status((short) 0)
                .createTime(new Date())
                .build();

        AuthType authType = AuthType.of(userAuthApply.getAuthType());

        if (Objects.equals(userAuthApply.getExamineResultStatus(), ExamineResultStatus.PASS.getCode())) {
            message.setMessageTitle(authType.getName() + "认证通过通知");
            message.setMessageContent("您的认证申请已通过");
        } else if (Objects.equals(userAuthApply.getExamineResultStatus(), ExamineResultStatus.UNPASS.getCode())) {
            message.setMessageTitle(authType.getName() + "认证未通过通知");
            message.setMessageContent("您的认证申请未通过，原因：" + userAuthApply.getExamineResultMessage());
        }

        return message;
    }
}
